//
//  FocusedHouseViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/9.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "FocusedHouseViewController.h"
#import "HouseDetailViewController.h"
#import "UserHomepageViewController.h"

#import "EmptyView.h"

#import "HouseListTableViewCell.h"

#import "HttpServer.h"
#import "FocusedHouse.h"
#import "Team.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/UIButton+WebCache.h>
#import "MJRefresh.h"
#import "Utility.h"
#import "Constants.h"
#import "ACMacros.h"
#import <MobClick.h>
@interface FocusedHouseViewController () <UITableViewDelegate, UITableViewDataSource, HouseListTableViewCellDelegate>

@end

@implementation FocusedHouseViewController {
    NSMutableArray *focusedHousesArray;
    FocusedHouse *focusedHouse;
    NSMutableArray *teams;
    EmptyView *emptyView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureNavigationBar];
    [self configureTableView];
    [self configureEmptyView];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadFocusData];
    [MobClick beginLogPageView:@"关注房源页"];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"关注房源页"];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Configuring the view’s layout behavior
- (void)configureNavigationBar {
    self.title = @"关注房源";
    self.navigationItem.hidesBackButton = true;
    UIImage *backImage = [[UIImage imageNamed:@"back-18-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithImage:backImage style:UIBarButtonItemStyleDone target:self action:@selector(clickToPopBack)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    self.navigationItem.leftBarButtonItem = leftBarButton;
}

- (void)configureTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height - 64)];
    [self.view addSubview:self.tableView];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:RGBACOLOR(240, 240, 240, 1)];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView registerNib:[UINib nibWithNibName:@"HouseListTableViewCell" bundle:nil] forCellReuseIdentifier:@"HouseListTableViewCell"];
}

- (void)configureEmptyView {
    emptyView = [[EmptyView alloc]init];
    emptyView = [[[NSBundle mainBundle]loadNibNamed:@"EmptyView" owner:nil options:nil] lastObject];
    [emptyView setFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height - 64)];
    [emptyView.emptyImage setImage:[UIImage imageNamed:@"OX_message156-128"]];
    [emptyView.titleLabel setText:@"暂无关注房源"];
    [emptyView.contentLabel setText:@"点击房源照片上的❤️关注房源吧"];
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (focusedHousesArray.count == 0) {
        emptyView.hidden = false;
        [self.tableView addSubview:emptyView];
    } else {
        emptyView.hidden = true;
    }
    return focusedHousesArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    focusedHouse = [[FocusedHouse alloc]initWithDic:focusedHousesArray[row]];
//    teams = [housesArray[row] objectForKey:@"teams"];
    HouseListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HouseListTableViewCell"];
    [cell setDelegate:self];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell.houseImageView sd_setImageWithURL:[NSURL URLWithString:focusedHouse.houseCover] placeholderImage:[UIImage new]];
    [cell.priceLabel setText:[NSString stringWithFormat:@"¥%d间",focusedHouse.houseSingRentFloor]];
    [cell.houseNameLabel setText:focusedHouse.houseCommunity];
    [cell.houseRemarkLabel setText:[NSString stringWithFormat:@"%@ %d室%d厅%d卫 - %dm² | 入住时间: %@",focusedHouse.houseRegion, focusedHouse.houseRoomNum, focusedHouse.houseHallNum, focusedHouse.houseToiletNum, focusedHouse.houseArea, focusedHouse.checkinTime]];
    if (focusedHouse.houseCheck) {
        [cell.houseCheckLabel setHidden:false];
        [cell.sourceLeading setConstant:30];
    } else {
        [cell.houseCheckLabel setHidden:true];
        [cell.sourceLeading setConstant:0];
    }
    [cell.houseSourceLabel setText:focusedHouse.houseFrom];
    NSArray *buttonArray = @[cell.headerButton_1, cell.headerButton_2, cell.headerButton_3, cell.headerButton_4, cell.headerButton_5];
    for (UIButton *button in buttonArray) {
        button.hidden = true;
    }
    teams = [NSMutableArray arrayWithArray:focusedHouse.teams];
    for (int i = 0; i < teams.count; i++) {
        if (i < buttonArray.count) {
            UIButton *button = buttonArray[i];
            button.hidden = false;
            Team *team = [[Team alloc]initWithDic:teams[i]];
            [button sd_setBackgroundImageWithURL:[NSURL URLWithString:team.leaderAvatar] forState:UIControlStateNormal];
        }
    }
//    if (teams.count == 0) {
//        [cell.joinTeamNumber setHidden:true];
//        [cell.noChiefLabel setHidden:false];
//        [cell.noChiefLabel setText:@"这套新鲜的房源还没有室长，快抢先成为室长吧"];
//    } else {
//        [cell.joinTeamNumber setText:[NSString stringWithFormat:@"%lu个室长招募中",(unsigned long)teams.count]];
//        [cell.joinTeamNumber setHidden:false];
//        [cell.noChiefLabel setHidden:true];
//    }

    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    House *house = [[House alloc]initWithDic:[focusedHousesArray[row] objectForKey:@"house"]];
    NSNumber *code = [[NSNumber alloc]initWithInteger:[[house.limits[0] objectForKey:@"code"] integerValue]];
    switch ([code integerValue]) {
        case 1:
            return Main_Screen_Width * 0.6 + 123;
            break;
        default:
            return Main_Screen_Width * 0.6 + 174;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc]init];
    [header setBackgroundColor:RGBACOLOR(240, 240, 240, 1)];
    return header;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    HouseDetailViewController *detailVC = [[HouseDetailViewController alloc]init];
    if (focusedHousesArray[row] == nil) {
    } else {
        focusedHouse = [[FocusedHouse alloc]initWithDic:focusedHousesArray[row]];
        detailVC.houseId = focusedHouse.houseId;
        [self.navigationController pushViewController:detailVC animated:true];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return true;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    if (focusedHousesArray[row] == nil) {
    } else {
        [focusedHousesArray removeObjectAtIndex:row];
        [self.tableView reloadData];
        focusedHouse = [[FocusedHouse alloc]initWithDic:focusedHousesArray[row]];
        [self deleteFocusWithFavoriteId:focusedHouse.favoriteId];
    }
}

#pragma mark - Triggering Methods
- (void)clickToPopBack {
    [self.navigationController popToRootViewControllerAnimated:true];
}

#pragma mark - Network methods
- (void)loadFocusData {
    [HttpServer getFocusedHousesSuccessBlock:^(NSDictionary *focusDic) {
        focusedHousesArray = [[NSMutableArray alloc]initWithArray:[focusDic objectForKey:@"favorites"]];
        [self.tableView reloadData];
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
    }];
}

- (void)deleteFocusWithFavoriteId:(NSString *)favoriteId {
    [HttpServer deleteFavoriteHouseWithId:favoriteId WithSuccessBlock:^(NSDictionary *successDic) {
        NSLog(@"%@",successDic);
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
    }];
}

#pragma mark - Table view cell delegate
- (void)headerButtonClickedWithTag:(NSInteger)tag WithIndex:(NSInteger)index{
    FocusedHouse *tempfocusedHouse = [[FocusedHouse alloc]initWithDic:focusedHousesArray[index]];
    NSArray *tempTeams = tempfocusedHouse.teams;
    NSDictionary *leaderDic = tempTeams[tag];
    Leader *leader = [[Leader alloc]initWithDic:leaderDic];
    UserHomepageViewController *userHomepageVC = [[UserHomepageViewController alloc]init];
    userHomepageVC.userId = leader.leaderId;
    userHomepageVC.userName = leader.leaderName;
    [self.navigationController pushViewController:userHomepageVC animated:true];
}


@end
